package cn.pku.ss.fa.sessionbean;



import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.ejb.*;
import javax.persistence.*;

import cn.pku.ss.fa.bean.*;
import cn.pku.ss.fa.entity.*;

import java.util.*;

@Stateless
@Local ({UserManagerLocal.class})
public class UserManager implements UserManagerLocal {

	@PersistenceContext
	protected EntityManager manager;
	
	
	
	public boolean registerUser(PersonalBean userBean) {
		System.out.println("Enter insertStudent method");
		
		//Query query = manager.createQuery(arg0)
		
		User user = new User();
		user.setUserName(userBean.getUserName());
		user.setPassword(userBean.getPassword());
		user.setRealName(userBean.getRealName());
		user.setStatus(userBean.getStatus());
		System.out.println("Status: " + userBean.getStatus());
		
		City city = manager.find(City.class, userBean.getCity().getId());
		user.setCity(city);
	
		
		SimpleDateFormat   sdt   =   new   SimpleDateFormat("yyyy-MM-dd");   
		Date   date = null;
		try {
		date =   sdt.parse(userBean.getBirthDay());
		} catch (Exception e) {
			e.printStackTrace();
		}
		user.setBirthday(date);
		
		user.setImageURL(userBean.getProfile());
		user.setQq(userBean.getQq());
		user.setMsn(userBean.getMsn());
		
		user.setPhone(userBean.getPhoneNumber());
		
		user.setSite(userBean.getSite());
	    
		List<EducationExperience> educationBeans = userBean.getEducationExperiences();
		System.out.println("*******************size: " + educationBeans.size());
		Set<Education> educations = new HashSet<Education>();
		try {
		for (int i = 0; i < educationBeans.size(); i++ ) {
			EducationExperience educationBean = educationBeans.get(i);
			Education education = new Education();
			education.setBeginTime(sdt.parse(educationBean.getStartDate()));
			education.setEndTime(sdt.parse(educationBean.getEndDate()));
			education.setSchoolName(educationBean.getSchool());
			education.setExperience(educationBean.getExperience());
			educations.add(education);
			
		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		user.setEducations(educations);
		System.out.println("***********size: " + user.getEducations().size());
		
		List<WorkExperience> workBeans = userBean.getWorkExperiences();
		Set<Work> works = new HashSet<Work>();
		try {
		for (int i = 0; i < workBeans.size(); i++ ) {
			WorkExperience workBean = workBeans.get(i);
			Work work = new Work();
			work.setCompanyName(workBean.getCompany());
			work.setDescription(workBean.getDescription());
			work.setPosition(workBean.getPosition());
			
			works.add(work);
			
		}
		} catch (Exception e) {
			e.printStackTrace();
		}
		user.setWorks(works);
		
		
		
		
		
		
		try {
		manager.persist(user);
		} catch (Exception e) {
			return false;
		}
		
		Integer ID = user.getId();
		if (ID != null)
			System.out.println("Id is " + ID);
		else System.out.println("null");
		
		System.out.println("Complete persist");
		return true;
	}
	
	public PersonalBean login(String name, String password) {
		
		Query query = manager.createQuery("select p from User p where p.userName = ?1 ");
		query.setParameter(1, name);
		
		List users = query.getResultList();
		System.out.println("users size: " + users.size());
		if (users.size() != 1)
			return null;
		else {
			User user = (User)users.get(0);
			System.out.println("Get User");
			if (!password.equals(user.getPassword())) {
				
				return null;
			}
			else {
				
				PersonalBean userBean = new PersonalBean();
				userBean.setId(user.getId());
				return userBean;
			}
		}
		
		
		
	}
	
	
	public PersonalBean findUserByUserId(int userId) {
		User user = manager.find(User.class, userId);
		if (user == null)
			return null;
		
		PersonalBean userBean = new PersonalBean();
		userBean.setId(user.getId());
		userBean.setUserName(user.getUserName());
		userBean.setPassword(user.getPassword());
		userBean.setRealName(user.getRealName());
		userBean.setStatus(user.getStatus());
		City city = user.getCity();
		CityBean cityBean = new CityBean();
		cityBean.setId(city.getId());
		cityBean.setCityName(city.getName());
		userBean.setCity(cityBean);
		userBean.setProvince(city.getProvince().getName());
		userBean.setBirthDay(String.valueOf(user.getBirthday()));
		
		userBean.setProfile(user.getImageURL());
		userBean.setQq(user.getQq());
		userBean.setMsn(user.getMsn());
		userBean.setPhoneNumber(user.getPhone());
		userBean.setSite(user.getSite());
		
		List<EducationExperience> educationBeans = new ArrayList<EducationExperience>();
		Set<Education> educations = user.getEducations();
		if (educations != null)
		for (Iterator iter = educations.iterator(); iter.hasNext(); ) {
			Education education = (Education)iter.next();
			EducationExperience educationExperience = new EducationExperience();
			educationExperience.setSchool(education.getSchoolName());
			educationExperience.setExperience(education.getExperience());
			educationExperience.setStartDate(String.valueOf(education.getBeginTime()));
			educationExperience.setEndDate(String.valueOf(education.getEndTime()));
			educationBeans.add(educationExperience);
		}
		userBean.setEducationExperiences(educationBeans);
		
		List<WorkExperience> workBeans = new ArrayList<WorkExperience>();
		Set<Work> works = user.getWorks();
		if (works != null)
			for (Iterator iter = works.iterator(); iter.hasNext(); ) {
				Work work = (Work)iter.next();
				WorkExperience workExperience = new WorkExperience();
				workExperience.setCompany(work.getCompanyName());
				workExperience.setDescription(work.getDescription());
				workExperience.setPosition(work.getPosition());
				workBeans.add(workExperience);
			}
		
		userBean.setWorkExperiences(workBeans);
		
		return userBean;
	}
	
	public void updateUserStatusByUserId(int userId, String userStatus) {
		User user = manager.find(User.class, userId);
		user.setStatus(userStatus);
	}
	
	public boolean makeFriends(int userId1, int userId2) {
		try {
		User user1 = manager.find(User.class, userId1);
		User user2 = manager.find(User.class, userId2);
		
		user1.getFriends().add(user2);
		user2.getFriends().add(user1);
		} catch (Exception e) {
			return false;
		}
		return true;
	}
	
	public boolean isFriendship(int userId1, int userId2) {
		User user1 = manager.find(User.class, userId1);
		User user2 = manager.find(User.class, userId2);
		return user1.getFriends().contains(user2);
			
	}
	
	public boolean updateUserProfile(int userId, String newProfile) {
		try {
		User user = manager.find(User.class, userId);
		user.setImageURL(newProfile);
		} catch (Exception e) {
			return false;
		}
		
		return true;
		
	}
	
	public List<FriendLittleBean> getFriends(int Id) {
		User person = manager.find(User.class, Id);
		if (person == null)
			return null;
		
		Set<User> friends = person.getFriends();
		List<FriendLittleBean> friendBeans = new ArrayList<FriendLittleBean>();
		for (Iterator iter = friends.iterator(); iter.hasNext(); ) {
			User user = (User)iter.next();
			FriendLittleBean friendLittleBean = new FriendLittleBean();
			friendLittleBean.setCity(user.getCity().getName());
			friendLittleBean.setId(user.getId());
			friendLittleBean.setImageURL(user.getImageURL());
			friendLittleBean.setName(user.getUserName());
			friendLittleBean.setPageURL(user.getSite());
			friendLittleBean.setProvince(user.getCity().getProvince().getName());
			friendLittleBean.setStatus(user.getStatus());
			Set<Education> educations = user.getEducations();
			Iterator eduIter = educations.iterator();
			Education education = eduIter.hasNext() ? (Education)eduIter.next() : null;
			String universityName = education == null ? null : education.getSchoolName();
			friendLittleBean.setUniversityName(universityName);
			friendBeans.add(friendLittleBean);
		}
		
		return friendBeans;
	}
	
	public List<FriendLittleBean> getFriendsByName(String name) {
		Query query = manager.createQuery("select p from User p where p.realName = ?1 ");
		query.setParameter(1, name);
		
		List users = query.getResultList();
		
		List<FriendLittleBean> friends = new ArrayList<FriendLittleBean>();
		
		if (users != null)
			for (Iterator iter = users.iterator(); iter.hasNext(); ) {
				User user = (User)iter.next();
				FriendLittleBean friendLittleBean = new FriendLittleBean();
				friendLittleBean.setCity(user.getCity().getName());
				friendLittleBean.setId(user.getId());
				friendLittleBean.setImageURL(user.getImageURL());
				friendLittleBean.setName(user.getUserName());
				friendLittleBean.setPageURL(user.getSite());
				friendLittleBean.setProvince(user.getCity().getProvince().getName());
				friendLittleBean.setStatus(user.getStatus());
				Set<Education> educations = user.getEducations();
				Iterator eduIter = educations.iterator();
				
				
				Education education = eduIter.hasNext() ? (Education)eduIter.next() : null;
				String universityName = education == null ? null : education.getSchoolName();
				friendLittleBean.setUniversityName(universityName);
				friends.add(friendLittleBean);
			}
		
		return friends;
	}
}
